# Copyright (c) 2019 Presto Labs Pte. Ltd.
# Author: xguo

import collections
import functools
import logging

from absl import app, flags

from coin.base.timestamp import get_timestamp
from coin.experimental.xguo.fruit.util.util import VolatilityCalculator
from coin.experimental.xguo.fruit.util.record_writer import RecordWriter
from coin.experimental.xguo.fruit.base.single_product import SingleProductPriceCalculator
from coin.experimental.xguo.fruit.base.util import MovingWindowData
from coin.experimental.xguo.fruit.base.strategy_sim_base import (
    BaseSimStrategy,
    BaseStrategyConfig,
)

FLAGS = flags.FLAGS


class Pricer(object):
  def __init__(self, product):
    self._mw = MovingWindowData(300)
    self._product = product
    self._price_calculator = SingleProductPriceCalculator(product)

  def update(product, book):
    if product != self._product:
      logging.error('product %s, book product %s', self._product, product)
      return

    self._price_calculator.update(book)
    self._mw.update(book.timestamp, self._price_calculator.midp)

  def calculate_edge(self):
    pass


class PearSimStrategy(BaseSimStrategy):
  def __init__(self, config):
    super().__init__(config)
    self.pnl_report = []
    self._pricers = collections.defaultdict(dict)
    self._fill_stats = collections.defaultdict(lambda: None)
    sub_req = self.strategy_config.strategy_core_config['trade_subreq']
    self._trade_mea = SubscriptionRequest.from_str(sub_req)
    event_clock_scheduler.add_periodic_task(1800, self.log_sim_time)
    event_clock_scheduler.add_periodic_task(300, self.pnl_snapshot)
    event_clock_scheduler.add_periodic_task(3600, self.save_sim_result)
    self._renew_tick_done = False

  def on_book(self, product, book):
    vol_calculator = self._vol_calculator[book.product]

    self._pricer.update(, price_calculator.midp)
    if vol_calculator.is_ready():
      vol = vol_calculator.get_volatility()
      data = {'timestamp': book.timestamp, 'symbol': book.product.full_symbol, 'volatility': vol}
      self._vol_writer.write(data)

  def on_trade(self, product, trade_event):
    pass


def main(_):
  config = BaseStrategyConfig.from_file(FLAGS.config)
  strategy = PearSimStrategy(config)
  strategy.run()


if __name__ == '__main__':
  flags.DEFINE_string('config', None, 'Strategy config file.')

  logging.basicConfig(level='INFO', format='%(levelname)s %(asctime)s %(name)s] %(message)s')
  app.run(main)
